package team.nine.kuaichezuche.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import team.nine.kuaichezuche.service.VerificationCodeService;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/verification")
public class VerificationCodeController {
    
    @Resource
    private VerificationCodeService verificationCodeService;
    
    /**
     * 生成验证码
     * @param key 验证码的键（通常是手机号或邮箱）
     * @return 包含验证码的响应
     */
    @PostMapping("/generate")
    public ResponseEntity<Map<String, Object>> generateCode(@RequestParam String key) {
        Map<String, Object> response = new HashMap<>();
        try {
            String code = verificationCodeService.generateVerificationCode(key);
            
            response.put("status", "success");
            response.put("message", "验证码生成成功");
            response.put("code", code); // 注意：实际生产环境中，这里不应该直接返回验证码给前端
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("status", "error");
            response.put("message", "生成验证码失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }
    
    /**
     * 验证验证码
     * @param key 验证码的键
     * @param code 用户输入的验证码
     * @return 验证结果
     */
    @PostMapping("/verify")
    public ResponseEntity<Map<String, Object>> verifyCode(@RequestParam String key, @RequestParam String code) {
        Map<String, Object> response = new HashMap<>();
        try {
            boolean isValid = verificationCodeService.verifyCode(key, code);
            
            if (isValid) {
                response.put("status", "success");
                response.put("message", "验证码验证成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("status", "error");
                response.put("message", "验证码不正确或已过期");
                return ResponseEntity.status(400).body(response);
            }
        } catch (Exception e) {
            response.put("status", "error");
            response.put("message", "验证验证码失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }
}